package dao

import (
	"errors"
	"fmt"
	"log"
	"regexp"
	"strconv"
	"strings"
	"time"
	"user_srv/basic/userproto"
	"user_srv/handler/models"
)

// 创建个人用户充值记录
func PersonalUserRecharge(in *__.PersonalUserRechargeReq) (*models.PersonalUserRecharge, error) {
	// 1. 参数验证
	if err := validateRechargeRequest(in); err != nil {
		log.Printf("充值记录参数验证失败: %v", err)
		return nil, fmt.Errorf("参数验证失败: %w", err)
	}

	// 2. 解析充值时间
	rechargeTime, err := parseRechargeTime(in.RechargeTime)
	if err != nil {
		log.Printf("充值时间解析失败: %v", err)
		return nil, fmt.Errorf("充值时间格式错误: %w", err)
	}

	// 3. 验证充值金额合理性
	if err := validateRechargeAmount(in.RechargeAmountPrincipal, in.GiftAmount, in.RechargeDiscount); err != nil {
		log.Printf("充值金额验证失败: %v", err)
		return nil, fmt.Errorf("充值金额验证失败: %w", err)
	}

	// 4. 检查用户是否存在
	if err := validateUserExists(in.UserId); err != nil {
		log.Printf("用户验证失败: %v", err)
		return nil, fmt.Errorf("用户验证失败: %w", err)
	}

	// 5. 检查充值流水号是否已存在
	if err := validateTransactionIdUnique(in.RechargeTransactionId); err != nil {
		log.Printf("流水号验证失败: %v", err)
		return nil, fmt.Errorf("流水号验证失败: %w", err)
	}

	// 6. 创建充值记录
	recharge := models.PersonalUserRecharge{
		UserId:                  in.UserId,
		RechargeTransactionId:   in.RechargeTransactionId,
		UserName:                in.UserName,
		Mobile:                  in.Mobile,
		UserType:                in.UserType,
		RechargeTime:            rechargeTime,
		RechargeAmountPrincipal: in.RechargeAmountPrincipal,
		GiftAmount:              in.GiftAmount,
		RechargeDiscount:        in.RechargeDiscount,
		ThirdPartyTransactionId: in.ThirdPartyTransactionId,
		RechargeChannel:         in.RechargeChannel,
	}

	// 7. 保存到数据库
	if err := recharge.Create(); err != nil {
		log.Printf("创建充值记录失败: %v", err)
		return nil, fmt.Errorf("创建充值记录失败: %w", err)
	}

	log.Printf("成功创建充值记录，用户ID: %d, 流水号: %s", in.UserId, in.RechargeTransactionId)
	return &recharge, nil
}

// 查询个人用户充值记录列表
func PersonalUserRechargeList(in *__.PersonalUserRechargeListReq) (*__.PersonalUserRechargeListResp, error) {
	var recharge models.PersonalUserRecharge

	// 设置默认分页参数
	page := int(in.Page)
	pageSize := int(in.PageSize)
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 10
	}

	// 查询数据
	list, total, err := recharge.GetList(
		in.RechargeTransactionId,
		in.Mobile,
		in.UserName,
		in.RechargeChannel,
		in.StartTime,
		in.EndTime,
		page,
		pageSize,
	)
	if err != nil {
		return nil, errors.New("查询充值记录失败: " + err.Error())
	}

	// 转换为响应格式
	var items []*__.PersonalUserRechargeItem
	for _, item := range list {
		items = append(items, &__.PersonalUserRechargeItem{
			Id:                      int32(item.Id),
			UserId:                  item.UserId,
			RechargeTransactionId:   item.RechargeTransactionId,
			UserName:                item.UserName,
			Mobile:                  item.Mobile,
			UserType:                item.UserType,
			RechargeTime:            item.RechargeTime.Format("2006-01-02 15:04:05"),
			RechargeAmountPrincipal: item.RechargeAmountPrincipal,
			GiftAmount:              item.GiftAmount,
			RechargeDiscount:        item.RechargeDiscount,
			ThirdPartyTransactionId: item.ThirdPartyTransactionId,
			RechargeChannel:         item.RechargeChannel,
		})
	}

	return &__.PersonalUserRechargeListResp{
		List:     items,
		Total:    int32(total),
		Page:     int32(page),
		PageSize: int32(pageSize),
	}, nil
}

// validateRechargeRequest 验证充值请求参数
func validateRechargeRequest(in *__.PersonalUserRechargeReq) error {
	if in == nil {
		return errors.New("请求参数不能为空")
	}

	// 验证必填字段
	if in.UserId <= 0 {
		return errors.New("用户ID必须大于0")
	}

	if strings.TrimSpace(in.RechargeTransactionId) == "" {
		return errors.New("充值流水号不能为空")
	}

	if strings.TrimSpace(in.UserName) == "" {
		return errors.New("用户名不能为空")
	}

	if strings.TrimSpace(in.Mobile) == "" {
		return errors.New("手机号不能为空")
	}

	// 验证手机号格式
	if !isValidMobile(in.Mobile) {
		return errors.New("手机号格式不正确")
	}

	if strings.TrimSpace(in.RechargeChannel) == "" {
		return errors.New("充值渠道不能为空")
	}

	if strings.TrimSpace(in.RechargeAmountPrincipal) == "" {
		return errors.New("充值金额不能为空")
	}

	// 验证流水号格式（通常为数字或字母数字组合）
	if !isValidTransactionId(in.RechargeTransactionId) {
		return errors.New("充值流水号格式不正确")
	}

	return nil
}

// parseRechargeTime 解析充值时间
func parseRechargeTime(timeStr string) (time.Time, error) {
	if strings.TrimSpace(timeStr) == "" {
		return time.Now(), nil
	}

	// 尝试多种时间格式
	formats := []string{
		"2006-01-02 15:04:05",
		"2006-01-02T15:04:05Z",
		"2006-01-02T15:04:05",
		"2006-01-02",
	}

	for _, format := range formats {
		if t, err := time.Parse(format, timeStr); err == nil {
			// 验证时间不能是未来时间
			if t.After(time.Now()) {
				return time.Time{}, errors.New("充值时间不能是未来时间")
			}
			// 验证时间不能太早（比如超过1年）
			if t.Before(time.Now().AddDate(-1, 0, 0)) {
				return time.Time{}, errors.New("充值时间不能超过1年")
			}
			return t, nil
		}
	}

	return time.Time{}, errors.New("时间格式不正确")
}

// validateRechargeAmount 验证充值金额合理性
func validateRechargeAmount(principal, gift, discount string) error {
	// 验证充值金额
	principalAmount, err := parseAmount(principal)
	if err != nil {
		return fmt.Errorf("充值金额格式错误: %w", err)
	}

	if principalAmount <= 0 {
		return errors.New("充值金额必须大于0")
	}

	if principalAmount > 100000 { // 单次充值限额10万
		return errors.New("单次充值金额不能超过10万元")
	}

	// 验证赠送金额
	if gift != "" {
		giftAmount, err := parseAmount(gift)
		if err != nil {
			return fmt.Errorf("赠送金额格式错误: %w", err)
		}
		if giftAmount < 0 {
			return errors.New("赠送金额不能为负数")
		}
		if giftAmount > principalAmount {
			return errors.New("赠送金额不能超过充值金额")
		}
	}

	// 验证折扣
	if discount != "" {
		discountRate, err := parseDiscount(discount)
		if err != nil {
			return fmt.Errorf("充值折扣格式错误: %w", err)
		}
		if discountRate <= 0 || discountRate > 1 {
			return errors.New("充值折扣必须在0-1之间")
		}
	}

	return nil
}

// validateUserExists 验证用户是否存在
func validateUserExists(userId int32) error {
	var user models.User
	user.Id = uint64(userId)
	err := user.GetUserById()
	if err != nil {
		return errors.New("用户不存在")
	}
	if user.Id == 0 {
		return errors.New("用户不存在")
	}
	return nil
}

// validateTransactionIdUnique 验证流水号唯一性
func validateTransactionIdUnique(transactionId string) error {
	var existingRecharge models.PersonalUserRecharge
	existingRecharge.RechargeTransactionId = transactionId
	err := existingRecharge.GetByTransactionId()
	if err == nil {
		return errors.New("充值流水号已存在")
	}
	return nil
}

// isValidMobile 验证手机号格式
func isValidMobile(mobile string) bool {
	// 简单的手机号格式验证
	matched, _ := regexp.MatchString(`^1[3-9]\d{9}$`, mobile)
	return matched
}

// isValidTransactionId 验证流水号格式
func isValidTransactionId(transactionId string) bool {
	// 流水号应该是字母数字组合，长度在6-32之间
	matched, _ := regexp.MatchString(`^[A-Za-z0-9]{6,32}$`, transactionId)
	return matched
}

// parseAmount 解析金额字符串
func parseAmount(amountStr string) (float64, error) {
	amountStr = strings.TrimSpace(amountStr)
	if amountStr == "" {
		return 0, nil
	}
	return strconv.ParseFloat(amountStr, 64)
}

// parseDiscount 解析折扣字符串
func parseDiscount(discountStr string) (float64, error) {
	discountStr = strings.TrimSpace(discountStr)
	if discountStr == "" {
		return 1.0, nil
	}
	return strconv.ParseFloat(discountStr, 64)
}
